package com.haochang.chunkvod.view.vod.activity;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseEditText;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.database.order.GoodsInfoDao;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.JoinListUtils;
import com.haochang.chunkvod.app.utils.SaleUtils;
import com.haochang.chunkvod.app.utils.TimeUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.model.order.Flavor;
import com.haochang.chunkvod.model.order.FoodDetailInfo;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.model.order.Standard;
import com.haochang.chunkvod.tools.vod.goods.ShoppingCartManager;
import com.haochang.chunkvod.tools.vod.other.MaxIntegerUtil;
import com.haochang.chunkvod.view.vod.dialog.KeyBoardDialog;
import com.haochang.chunkvod.view.vod.flavor.FlavorItem;
import com.haochang.chunkvod.view.vod.flavor.FlavorSelectView;
import com.haochang.chunkvod.view.vod.flavor.SizeSelectView;
import com.haochang.chunkvod.view.vod.flavor.flavorViewGroup;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**
 * @author qintao
 *         created at 2016/8/30 12:25
 *         点餐dialog添加框
 */

public class OrderDialogActivity extends BaseActivity implements KeyBoardDialog.KeyBoardOnSureListener
{
	private ActivityDialogEnum activityDialogEnum = ActivityDialogEnum.DEFAULT;
	private BaseTextView tv_title;
	private BaseTextView tv_totalPrice;
	private BaseTextView tv_already;
	private Button btn_xia_dan;
	private Button btn_shop_cart;
	private ImageView img_close;
	private BaseTextView tv_add_flavor;
	private LinearLayout lay_flavor;
	private BaseTextView tv_cut_1;
	private BaseTextView tv_add_1;
	private BaseTextView tv_left_name;
	private BaseEditText tv_content;
	private LinearLayout lay_size;
	private GoodsInfo goodsInfo = null;
	private List<LinearLayout> views = new LinkedList<LinearLayout>();
	private List<SizeSelectView> sizeSelectViews = new LinkedList<SizeSelectView>();
	private boolean isTakeOut;//是否是外带
	private EditText et_delivery_address;//送餐地点et
	private int totalNum = 0;
	private String leftName = "";
	private boolean is_goodsSwap = false;//商品是否是更换商品
	private FoodDetailInfo swapInfo = null;
	private int orgPrice = 0;//原来的价格
	/**
	 * 剩余数量
	 */
	private int surplusNumber = 0;
	/**
	 * 当前分项数量
	 */
	private int currentViewNumber = 0;
	/**
	 * 当前点击的分项值
	 */
	private Integer currentViewValue = 0;
	/**
	 * 其他已选分项已选总数量
	 */
	private int otherTotalNumber = 0;
	/**
	 * 规格提示信息
	 */
	private String standardMsg = "";

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public void receiveParam()
	{
		goodsInfo = (GoodsInfo) getIntent().getSerializableExtra(IntentKey.GOODSINFO);
		orgPrice = goodsInfo.getPrice();
		swapInfo = (FoodDetailInfo) getIntent().getSerializableExtra(IntentKey.GOODSSWAP);
		is_goodsSwap = getIntent().getBooleanExtra(IntentKey.IS_GOODSSWAP, false);
		isTakeOut = getIntent().getBooleanExtra(IntentKey.ORDER_TAKEOUT, false);
		surplusNumber = goodsInfo.getSurplus();
		activityDialogEnum = (ActivityDialogEnum) getIntent().getSerializableExtra(IntentKey.ACTIVITY_ENUM);
		leftName = getIntent().getStringExtra(IntentKey.CUSTOM_DIALOG_LEFT_NAME);
	}

	@Override
	public void initData()
	{

	}

	@Override
	public void initViews()
	{
		int contentViewResId = getLayoutForType(activityDialogEnum);
		if (contentViewResId < 0)
			return;
		setContentView(contentViewResId);
		//共同属性
		tv_title = (BaseTextView) findViewById(R.id.tv_title);
		tv_title.setText(goodsInfo.getGoodsName());
		img_close = (ImageView) findViewById(R.id.img_close);
		if (isTakeOut)
		{
			FrameLayout frameLayout = (FrameLayout) findViewById(R.id.includeAddress);
			frameLayout.setVisibility(View.VISIBLE);
			et_delivery_address = (EditText) frameLayout.findViewById(R.id.et_delivery_address);
			et_delivery_address.requestFocus();
			et_delivery_address.setSelection(et_delivery_address.getText().toString().length());
		}

		img_close.setOnClickListener(mOnBaseClickListener);
		tv_totalPrice = (BaseTextView) findViewById(R.id.tv_totalPrice);
		btn_xia_dan = (Button) findViewById(R.id.btn_xia_dan);
		btn_shop_cart = (Button) findViewById(R.id.btn_shop_cart);
		if (is_goodsSwap)
		{
			findViewById(R.id.differencePrice).setVisibility(View.VISIBLE);
			btn_xia_dan.setVisibility(View.GONE);
			btn_shop_cart.setText("确定");
		} else if (TextUtils.equals(getIntent().getAction(), "PackageDetailsActivity"))
		{
			btn_xia_dan.setVisibility(View.GONE);
		} else
		{
			btn_xia_dan.setVisibility(View.VISIBLE);
		}
		btn_xia_dan.setOnClickListener(mOnBaseClickListener);
		btn_shop_cart.setOnClickListener(mOnBaseClickListener);
		switch (activityDialogEnum)
		{
		case SIZE:
			lay_size = (LinearLayout) findViewById(R.id.lay_size);
		case PACKAGE_TYPE:
		case DEFAULT:
			tv_cut_1 = (BaseTextView) findViewById(R.id.tv_cut_1);
			tv_add_1 = (BaseTextView) findViewById(R.id.tv_add_1);
			tv_content = (BaseEditText) findViewById(R.id.tv_content);
			tv_content.addTextChangedListener(textWatcher);
			tv_content.setOnClickListener(mOnBaseClickListener);
			tv_left_name = (BaseTextView) findViewById(R.id.tv_left_name);
			tv_left_name.setText(leftName);
			if (is_goodsSwap && TextUtils.equals(swapInfo.getOperateTypeId(), goodsInfo.getOperateTypeId()))
				tv_content.setText(String.valueOf(swapInfo.getQuantity()));
			else
				tv_content.setText("1");
			tv_cut_1.setOnClickListener(mOnBaseClickListener);
			tv_add_1.setOnClickListener(mOnBaseClickListener);
			if (goodsInfo.getGoods_type() == VodConstant.ACTIVE_TYPE)
			{
				tv_cut_1.setVisibility(View.GONE);
				tv_add_1.setVisibility(View.GONE);
				tv_content.setClickable(false);
				tv_content.setEnabled(false);
			}
			if (activityDialogEnum == ActivityDialogEnum.SIZE)
				showSize();
			break;
		case FLAVOR:
			tv_already = (BaseTextView) findViewById(R.id.tv_already);
			lay_flavor = (LinearLayout) findViewById(R.id.lay_flavor);
			tv_add_flavor = (BaseTextView) findViewById(R.id.tv_add_flavor);
			tv_add_flavor.setOnClickListener(mOnBaseClickListener);
			addFlavor();
			break;
		default:
			break;
		}
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.img_close:
				finish();
				break;
			case R.id.btn_xia_dan:
				if (isTakeOut && TextUtils.isEmpty(et_delivery_address.getText().toString()))
				{
					ToastUtils.showText(context, "请输入送餐地址");
					return;
				}
				if (isSurplusNumSatisfy() && goodsInfo.getGoods_type() != VodConstant.ACTIVE_TYPE)
				{
					ToastUtils.showText(OrderDialogActivity.this, goodsInfo.getGoodsName() + "仅剩" + surplusNumber + goodsInfo.getUnit());
					return;
				}
				if (activityDialogEnum == ActivityDialogEnum.DEFAULT)
				{
					goodsInfo.setOrderNum(Integer.parseInt(tv_content.getText().toString()));
					Intent intent = new Intent();
					intent.putExtra(IntentKey.GOODSINFO, goodsInfo);
					if (isTakeOut)
						intent.putExtra(IntentKey.ORDER_TAKEOUT_ADDRESS, et_delivery_address.getText().toString());
					setResult(RESULT_OK, intent);
					finish();
				} else if (activityDialogEnum == ActivityDialogEnum.SIZE)
				{
					goodsInfo.setOrderNum(Integer.parseInt(tv_content.getText().toString()));
					goodsInfo.setStandard(getStandard());
					if (!TextUtils.isEmpty(standardMsg))
					{
						ToastUtils.showText(context, standardMsg);
						return;
					}
					Intent intent = new Intent();
					if (isTakeOut)
						intent.putExtra(IntentKey.ORDER_TAKEOUT_ADDRESS, et_delivery_address.getText().toString());
					intent.putExtra(IntentKey.GOODSINFO, goodsInfo);
					setResult(RESULT_OK, intent);
					finish();
				} else
				{
					List<GoodsInfo> infoList = getGoodInfoList();
					if (!CollectionUtils.isEmpty(infoList))
					{
						JSONArray goodsArray = new JSONArray();
						for (GoodsInfo goodsInfo : infoList)
						{
							if (goodsInfo.getGoods_type() == VodConstant.RETAIL_TYPE)
							{
								JSONObject jsonObject = ShoppingCartManager.getGoodsDataJson(goodsInfo);
								goodsArray.put(jsonObject);
							}
						}
						Intent intent1 = new Intent();
						if (isTakeOut)
							intent1.putExtra(IntentKey.ORDER_TAKEOUT_ADDRESS, et_delivery_address.getText().toString());
						intent1.putExtra(IntentKey.GOODSARRAY, goodsArray.toString());
						setResult(RESULT_OK, intent1);
						finish();
					} else
						finish();
				}
				break;
			case R.id.btn_shop_cart:
				if (activityDialogEnum == ActivityDialogEnum.PACKAGE_TYPE)
				{
					String value = tv_content.getText().toString();
					int orderNum = Integer.parseInt(value);
					setResult(RESULT_OK, getIntent().putExtra(IntentKey.ORDERNUM, orderNum));
				} else
				{
					if (goodsInfo.getGoods_type() == VodConstant.ACTIVE_TYPE)
					{
						GoodsInfo info = GoodsInfoDao.getDao().queryBuilder(GoodsInfo.class, "bill_id", goodsInfo.getBillId(), "goods_id",
								goodsInfo.getGoodsId(), "goods_type", "2");
						if (null != info)
							ToastUtils.showText(OrderDialogActivity.this, "购物车已添加该活动，下单后可再次购买");
						else
							ShoppingCartManager.getActiveDataBeforeAddToShop(goodsInfo, true);
					} else if (goodsInfo.getGoods_type() == VodConstant.BUNDLE_TYPE)
					{
						if (isSurplusNumSatisfy())
						{
							ToastUtils.showText(OrderDialogActivity.this, goodsInfo.getGoodsName() + "仅剩" + surplusNumber + goodsInfo.getUnit());
							return;
						}
						String num = tv_content.getText().toString();
						int orderNum = Integer.parseInt(num);
						goodsInfo.setOrderNum(orderNum);
						ShoppingCartManager.getPackageDataBeforeAddToShop(goodsInfo, true);
					} else
					{
						if (isSurplusNumSatisfy())
						{
							ToastUtils.showText(OrderDialogActivity.this, goodsInfo.getGoodsName() + "仅剩" + surplusNumber + goodsInfo.getUnit());
							return;
						}
						String value = getStandard();
						if (!TextUtils.isEmpty(standardMsg))
						{
							ToastUtils.showText(context, standardMsg);
							return;
						}
						if (is_goodsSwap)
						{
							//更换商品
							String num = tv_content.getText().toString();
							int orderNum = Integer.parseInt(num);
							goodsInfo.setStandard(value);
							goodsInfo.setOrderNum(orderNum);
							Intent intent1 = new Intent();
							intent1.putExtra(IntentKey.GOODSINFO, goodsInfo);
							setResult(RESULT_OK, intent1);
						} else
						{
							addToGoods(value);
							setResult(RESULT_OK);
						}
					}
				}
				finish();
				break;
			case R.id.tv_add_flavor:
				if (getTotalNum() < surplusNumber)
				{
					addFlavor();
				} else
				{
					ToastUtils.showText(OrderDialogActivity.this, "已选数量已满");
				}
				break;
			case R.id.tv_add_1:
				onClickAddOne();
				break;
			case R.id.tv_cut_1:
				onClickCutOne();
				break;
			case R.id.tv_content:
				KeyBoardDialog keyBoardDialog = new KeyBoardDialog(OrderDialogActivity.this);
				keyBoardDialog.setKeyBoardOnSureListener(OrderDialogActivity.this);
				keyBoardDialog.show();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 判断下单或者加入购物车时剩余数量是否满足
	 * @return
	 */
	private boolean isSurplusNumSatisfy()
	{
		GoodsInfo info = GoodsInfoDao.getDao().queryBuilder(GoodsInfo.class, "bill_id", goodsInfo.getBillId(), "goods_id", goodsInfo.getGoodsId());
		if (activityDialogEnum == ActivityDialogEnum.FLAVOR)
		{
			return surplusNumber < (info == null ? getTotalNum() : (info.getOrderNum() + getTotalNum()));
		} else
		{
			String num = tv_content.getText().toString();
			int orderNum = Integer.parseInt(num);
			return surplusNumber < (info == null ? orderNum : (info.getOrderNum() + orderNum));
		}
	}

	/**
	 * 显示规格
	 */
	private void showSize()
	{
		try
		{
			JSONArray jsonArray = new JSONArray(goodsInfo.getStandard_types());
			for (int i = 0; i < jsonArray.length(); i++)
			{
				JSONObject object = jsonArray.optJSONObject(i);
				LinearLayout viewSize = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.common_size_item, null);
				final BaseTextView tv_select_name = (BaseTextView) viewSize.findViewById(R.id.tv_select_name);
				final BaseTextView tv_select_num = (BaseTextView) viewSize.findViewById(R.id.tv_select_num);
				SizeSelectView sizeSelectView = (SizeSelectView) viewSize.findViewById(R.id.sizeSelectView);
				tv_select_name.setText(object.optString("name"));
				sizeSelectView.setTag(R.id.standard_type_name, object.optString("name"));
				final int maxSelectNum = object.optInt("quantity");
				JSONArray defaultArray = object.optJSONArray("default_standard_ids");//默认选中的规格
				tv_select_num.setText(
						Html.fromHtml("已选" + "<font color=#f04e39>" + (defaultArray != null ? defaultArray.length() : 0) + "</font>" + "/" + maxSelectNum));
				JSONArray array = object.optJSONArray("standard");
				if (array != null && array.length() > 0)
				{
					sizeSelectView.setMaxSelectCount(maxSelectNum);
					for (int j = 0; j < array.length(); j++)
					{
						JSONObject jsonObject = array.optJSONObject(j);
						final Standard standard = new Standard();
						standard.setStandardTypeId(jsonObject.optString("standard_type_id"));
						standard.setStandardId(jsonObject.optString("standard_id"));
						standard.setStandardName(jsonObject.optString("name"));
						standard.setStandardPrice(jsonObject.optInt("price"));
						sizeSelectView.addTab(standard);
						if (defaultArray != null && defaultArray.length() > 0)
						{
							for (int k = 0; k < defaultArray.length(); k++)
							{
								String standard_id = defaultArray.getString(k);
								if (standard_id.equals(jsonObject.optString("standard_id")))
								{
									sizeSelectView.setSelectedTable(j, standard.getStandardId(), standard.getStandardName(), maxSelectNum);
									break;
								}
							}
						}
					}
				}
				sizeSelectView.setOnTabChangedListener(new SizeSelectView.OnTabChangedListener()
				{
					@Override
					public void onTabChanged(int current, String menuId, String name, int count)
					{
						tv_select_num.setText(Html.fromHtml("已选" + "<font color=#f04e39>" + count + "</font>" + "/" + maxSelectNum));
						if (goodsInfo.getDiscountPrice() <= 0)
						{
							int price = getStandardPrice();
							if (price > 0)
								goodsInfo.setPrice(price);
							else
								goodsInfo.setPrice(orgPrice);
							setCurrentStandardPrice();
						}
					}
				});
				sizeSelectViews.add(sizeSelectView);
				lay_size.addView(viewSize);
			}
			if (goodsInfo.getDiscountPrice() <= 0)
			{
				int price = getStandardPrice();
				if (price > 0)
					goodsInfo.setPrice(price);
				else
					goodsInfo.setPrice(orgPrice);
			}
			setAlreadySelectNum();
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 添加口味
	 * 当有多组口味的时候，隐藏前面的口味选项
	 */
	private void addFlavor()
	{
		currentViewNumber++;
		if (!CollectionUtils.isEmpty(views))
		{
			for (LinearLayout view : views)
			{
				view.findViewById(R.id.lin_flavor_view).setVisibility(View.GONE);
				view.findViewById(R.id.lin_add_view).setVisibility(View.GONE);
				BaseTextView tv_content_select = (BaseTextView) view.findViewById(R.id.tv_content_select);
				tv_content_select.setVisibility(View.VISIBLE);
				tv_content_select.setText(((BaseEditText) view.findViewById(R.id.tv_content)).getText().toString() + goodsInfo.getUnit());
				BaseTextView tv_flavor_info = (BaseTextView) view.findViewById(R.id.tv_flavor_info);
				tv_flavor_info.setMaxEms(15);
			}
		}
		final LinearLayout viewItem = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.common_dialog_flavor_add_item, null);
		final flavorViewGroup view_flavor = (flavorViewGroup) viewItem.findViewById(R.id.view_flavor);
		final BaseTextView tv_flavor_info = (BaseTextView) viewItem.findViewById(R.id.tv_flavor_info);
		final BaseEditText tv_content = (BaseEditText) viewItem.findViewById(R.id.tv_content);
		tv_content.addTextChangedListener(textWatcher);
		BaseTextView tv_cut_1 = (BaseTextView) viewItem.findViewById(R.id.tv_cut_1);
		BaseTextView tv_add_1 = (BaseTextView) viewItem.findViewById(R.id.tv_add_1);
		final LinearLayout lin_flavor_view = (LinearLayout) viewItem.findViewById(R.id.lin_flavor_view);
		try
		{
			JSONArray array = new JSONArray(goodsInfo.getTaste_types());
			if (array.length() > 0)
			{
				FlavorSelectView[] tabSwitcher = new FlavorSelectView[array.length()];
				for (int j = 0; j < array.length(); j++)
				{
					LinearLayout viewFlavor = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.common_dialog_flavor_add_item_flavor, null);
					final BaseTextView tv_flavor_title = (BaseTextView) viewFlavor.findViewById(R.id.tv_flavor_title);
					tabSwitcher[j] = (FlavorSelectView) viewFlavor.findViewById(R.id.tabSwitcher);
					JSONObject object = array.getJSONObject(j);
					tv_flavor_title.setText(object.optString("name"));
					JSONArray tastes = object.optJSONArray("tastes");
					if (tastes != null && tastes.length() > 0)
					{
						for (int k = 0; k < tastes.length(); k++)
						{
							JSONObject obj = tastes.getJSONObject(k);
							final Flavor flavor = new Flavor();
							flavor.setFlavorId(obj.optString("taste_id"));
							flavor.setFlavorName(obj.optString("name"));
							tabSwitcher[j].addTab(flavor);
						}
					}
					final int finalJ = j;
					tabSwitcher[j].setOnTabChangedListener(new FlavorSelectView.OnTabChangedListener()
					{
						@Override
						public void onTabChanged(int last, int current, String Id, String name)
						{
							BaseTextView viewTv = (BaseTextView) LayoutInflater.from(context).inflate(R.layout.common_dialog_flavor_add_item_name, null);
							viewTv.setText(name);
							viewTv.setTag(Id);
							viewTv.setTag(R.id.flavor_select_num, String.valueOf(finalJ));
							int count = view_flavor.getChildCount();
							boolean flag = false;
							if (count > 0)
							{
								for (int i = 0; i < count; i++)
								{
									BaseTextView view = (BaseTextView) view_flavor.getChildAt(i);
									if (view.getTag(R.id.flavor_select_num).equals(String.valueOf(finalJ)))
									{
										view.setText(name);
										view.setTag(Id);
										view.setTag(R.id.flavor_select_num, String.valueOf(finalJ));
										flag = true;
										break;
									}
								}
							}
							if (!flag)
							{
								view_flavor.addView(viewTv);
							}
							count = view_flavor.getChildCount();
							//取消当前选择的口味
							if (last == current)
							{
								for (int j = 0; j < count; j++)
								{
									BaseTextView tView = (BaseTextView) view_flavor.getChildAt(j);
									if (tView.getTag().equals(Id))
									{
										view_flavor.removeView(view_flavor.getChildAt(j));
										break;
									}
								}
							}
							//根据选择的口味显示文字
							count = view_flavor.getChildCount();
							if (count > 0)
							{
								String value = "";
								for (int j = 0; j < count; j++)
								{
									BaseTextView tView = (BaseTextView) view_flavor.getChildAt(j);
									if (j == count - 1)
										value += tView.getText().toString();
									else
										value += tView.getText().toString() + "；";
								}
								tv_flavor_info.setText("口味：" + value);
							} else
								tv_flavor_info.setText("口味：标准");
						}
					});
					lin_flavor_view.addView(viewFlavor);
				}
			}
		} catch (JSONException e)
		{
			e.printStackTrace();
		}
		tv_content.setTag(currentViewNumber);
		tv_content.setOnClickListener(new OnBaseClickListener()
		{

			@Override
			public void onBaseClick(View v)
			{
				currentViewValue = (Integer) tv_content.getTag();
				KeyBoardDialog keyBoardDialog = new KeyBoardDialog(OrderDialogActivity.this);
				keyBoardDialog.setKeyBoardOnSureListener(OrderDialogActivity.this);
				keyBoardDialog.show();
			}
		});

		tv_cut_1.setOnClickListener(new OnBaseClickListener()
		{
			@Override
			public void onBaseClick(View v)
			{
				int number = Integer.parseInt(tv_content.getText().toString());
				onClickCutOne(tv_content, number, viewItem);
			}
		});
		tv_add_1.setOnClickListener(new OnBaseClickListener()
		{
			@Override
			public void onBaseClick(View v)
			{
				int number = Integer.parseInt(tv_content.getText().toString());
				onClickAddOne(tv_content, number, getTotalNum());
			}
		});

		viewItem.setOnClickListener(new OnBaseClickListener()
		{
			@Override
			public void onBaseClick(View v)
			{
				if (!CollectionUtils.isEmpty(views))
				{
					for (LinearLayout view : views)
					{
						LinearLayout lin_add_view = (LinearLayout) view.findViewById(R.id.lin_add_view);
						BaseTextView tv_content_select = (BaseTextView) view.findViewById(R.id.tv_content_select);
						BaseTextView tv_flavor_info = (BaseTextView) view.findViewById(R.id.tv_flavor_info);
						BaseEditText tv_content = (BaseEditText) view.findViewById(R.id.tv_content);
						LinearLayout lin_flavor_view = (LinearLayout) view.findViewById(R.id.lin_flavor_view);
						if (v == view)
						{
							if (lin_flavor_view.getVisibility() == View.VISIBLE)
							{
								lin_flavor_view.setVisibility(View.GONE);
								lin_add_view.setVisibility(View.GONE);
								tv_content_select.setVisibility(View.VISIBLE);
								tv_content_select.setText(tv_content.getText().toString() + goodsInfo.getUnit());
								tv_flavor_info.setMaxEms(15);
							} else
							{
								lin_flavor_view.setVisibility(View.VISIBLE);
								lin_add_view.setVisibility(View.VISIBLE);
								tv_content_select.setVisibility(View.GONE);
								tv_flavor_info.setMaxEms(8);
							}
						} else
						{
							lin_flavor_view.setVisibility(View.GONE);
							lin_add_view.setVisibility(View.GONE);
							tv_content_select.setVisibility(View.VISIBLE);
							tv_content_select.setText(tv_content.getText().toString() + goodsInfo.getUnit());
							tv_flavor_info.setMaxEms(15);
						}
					}
				}
			}
		});
		views.add(viewItem);
		lay_flavor.addView(viewItem);
		setAlreadySelectNum();
	}

	/**
	 * 每次增加1个
	 */
	private void onClickAddOne()
	{
		int number = Integer.parseInt(tv_content.getText().toString());
		if (number < surplusNumber)
		{
			number = number + 1;
		} else
		{
			ToastUtils.showText(context, "不能再增加数量了");
		}
		tv_content.setText(String.valueOf(number));
	}

	/**
	 * 每次减少1个
	 */
	private void onClickCutOne()
	{
		int number = Integer.parseInt(tv_content.getText().toString());
		if (number > 1)
		{
			number = number - 1;
		} else
		{
			ToastUtils.showText(context, "不能再减少了");
		}
		tv_content.setText(String.valueOf(number));
	}

	/**
	 * 每次增加1个
	 */
	private void onClickAddOne(BaseEditText tv_content, int currentNumber, int total)
	{
		otherTotalNumber = total - currentNumber;
		if (currentNumber + otherTotalNumber < surplusNumber)
		{
			currentNumber = currentNumber + 1;
		} else
		{
			ToastUtils.showText(context, "不能再增加数量了");
		}
		tv_content.setText(String.valueOf(currentNumber));
	}

	/**
	 * 每次减少1个
	 */
	private void onClickCutOne(BaseEditText tv_content, int currentNumber, LinearLayout viewItem)
	{
		if (currentNumber > 1)
		{
			currentNumber = currentNumber - 1;
		} else if (currentViewNumber > 1)
		{
			currentViewNumber = currentViewNumber - 1;
			views.remove(viewItem);
			lay_flavor.removeView(viewItem);
		} else
		{
			ToastUtils.showText(context, "不能再减少了");
		}
		tv_content.setText(String.valueOf(currentNumber));
	}

	/**
	 * 获取所有分项的已选总量
	 *
	 * @return
	 */
	private int getTotalNum()
	{
		int totalNum = 0;
		for (int i = 0; i < views.size(); i++)
		{
			LinearLayout view = views.get(i);
			BaseEditText etView = (BaseEditText) view.findViewById(R.id.tv_content);
			String value = etView.getText().toString().trim();
			if (!TextUtils.isEmpty(value))
			{
				totalNum = totalNum + Integer.parseInt(value);
			}
		}
		return totalNum;
	}

	private TextWatcher textWatcher = new TextWatcher()
	{
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after)
		{

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count)
		{

		}

		@Override
		public void afterTextChanged(Editable s)
		{
			setAlreadySelectNum();
		}
	};

	/**
	 * 加入购物车
	 */
	public void addToGoods(String standard)
	{
		if (activityDialogEnum == ActivityDialogEnum.FLAVOR)
		{
			List<GoodsInfo> infoList = getGoodInfoList();
			List<GoodsInfo> dbInfoList = GoodsInfoDao.getDao().queryBuilderAll(GoodsInfo.class, "bill_id", goodsInfo.getBillId(), "goods_id",
					goodsInfo.getGoodsId(), "menu_id", goodsInfo.getMenuId(), "is_give", goodsInfo.is_give(), "is_present", goodsInfo.is_present());
			//合并相同口味的数据
			List<GoodsInfo> newInfoList = new ArrayList<GoodsInfo>();
			if (!CollectionUtils.isEmpty(infoList))
				newInfoList.addAll(infoList);
			if (!CollectionUtils.isEmpty(dbInfoList))
				newInfoList.addAll(dbInfoList);
			List<GoodsInfo> joinList = JoinListUtils.joinDataList(newInfoList);
			try
			{
				if (!CollectionUtils.isEmpty(joinList))
					GoodsInfoDao.getDao().updateOrCreateAll(GoodsInfo.class, joinList);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			goodsInfo.setOrderNum(goodsInfo.getOrderNum() + totalNum);
		} else
		{
			String value = tv_content.getText().toString();
			int orderNum = Integer.parseInt(value);
			GoodsInfo info = GoodsInfoDao.getDao().queryBuilder(GoodsInfo.class, "bill_id", goodsInfo.getBillId(), "goods_id", goodsInfo.getGoodsId(),
					"menu_id", goodsInfo.getMenuId(), "is_give", goodsInfo.is_give(), "is_present", goodsInfo.is_present());
			if (activityDialogEnum == ActivityDialogEnum.SIZE)
			{
				if (info != null && TextUtils.equals(info.getStandard(), standard))
				{
					updateData(info, orderNum);
				} else
					insertData(standard, orderNum);
			} else
			{
				if (info != null)
					updateData(info, orderNum);
				else
					insertData(standard, orderNum);
			}
		}
	}

	/**
	 * 修改数据库数据
	 * @param info
	 * @param orderNum
	 */
	private void updateData(GoodsInfo info, int orderNum)
	{
		info.setOrderTime(TimeUtils.getNowTime());
		info.setOrderNum(info.getOrderNum() + orderNum);
		GoodsInfoDao.getDao().update(GoodsInfo.class, info);
		goodsInfo.setOrderNum(goodsInfo.getOrderNum() + orderNum);
	}

	/**
	 * 插入数据
	 * @param standard
	 * @param orderNum
	 */
	private void insertData(String standard, int orderNum)
	{
		goodsInfo.setStandard(standard);
		goodsInfo.setOrderNum(orderNum);
		goodsInfo.setOrderTime(TimeUtils.getNowTime());
		GoodsInfoDao.getDao().insert(GoodsInfo.class, goodsInfo);
	}

	/**
	 * 获取最大规格价
	 *
	 * @return
	 */
	private int getStandardPrice()
	{
		List<Integer> list = new ArrayList<Integer>();
		int countParent = sizeSelectViews.size();
		int countChild = 0;
		try
		{
			for (int i = 0; i < countParent; i++)
			{
				SizeSelectView view = sizeSelectViews.get(i);
				countChild = view.getChildCount();
				for (int j = 0; j < countChild; j++)
				{
					FlavorItem tView = (FlavorItem) view.getChildAt(j);
					if (tView.isSelected())
					{
						list.add((Integer) tView.getTag(R.id.standard_price_id));
					}
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return CollectionUtils.isEmpty(list) ? 0 : MaxIntegerUtil.getMaxNumber(list);
	}

	/**
	 * 获取规格数据
	 *
	 * @return
	 */
	private String getStandard()
	{
		standardMsg = "";
		int countParent = sizeSelectViews.size();
		int countChild = 0;
		int maxSelect = 0;
		JSONArray array = new JSONArray();
		try
		{
			for (int i = 0; i < countParent; i++)
			{
				SizeSelectView view = sizeSelectViews.get(i);
				countChild = view.getChildCount();
				int selectNum = 0;
				for (int j = 0; j < countChild; j++)
				{
					JSONObject obj = new JSONObject();
					FlavorItem tView = (FlavorItem) view.getChildAt(j);
					if (tView.isSelected())
					{
						obj.put("id", tView.getTag(R.id.menu_value_id));
						obj.put("name", tView.getTag(R.id.menu_value_name));
						obj.put("price", tView.getTag(R.id.standard_price_id));
						obj.put("standardTypeId", tView.getTag(R.id.standard_type_id));
						array.put(obj);
						selectNum++;
					}
				}
				maxSelect = view.getMaxSelectCount();
				if (maxSelect != selectNum)
				{
					standardMsg = view.getTag(R.id.standard_type_name) + "必须选择" + maxSelect + "种规格";
					break;
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return array.length() > 0 ? array.toString() : "";
	}

	private List<GoodsInfo> getGoodInfoList()
	{
		List<GoodsInfo> infoList = new ArrayList<GoodsInfo>();
		int total = 0;
		for (int i = 0; i < views.size(); i++)
		{
			GoodsInfo info = new GoodsInfo();
			LinearLayout view = views.get(i);
			flavorViewGroup view_flavor = (flavorViewGroup) view.findViewById(R.id.view_flavor);
			BaseEditText etView = (BaseEditText) view.findViewById(R.id.tv_content);
			String value = etView.getText().toString().trim();
			int num = Integer.parseInt(value);
			totalNum = total + num;
			int count = view_flavor.getChildCount();
			JSONArray array = new JSONArray();
			for (int j = 0; j < count; j++)
			{
				BaseTextView tView = (BaseTextView) view_flavor.getChildAt(j);
				JSONObject obj = new JSONObject();
				try
				{
					obj.put("id", tView.getTag());
					obj.put("name", tView.getText());
					array.put(obj);
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
			info.setGoodsId(goodsInfo.getGoodsId());
			info.setRoomId(goodsInfo.getRoomId());
			info.setBillId(goodsInfo.getBillId());
			info.setMenuId(goodsInfo.getMenuId());
			info.setFlavor(array.length() > 0 ? array.toString() : "");
			info.setOrderNum(num);
			info.setGoodsName(goodsInfo.getGoodsName());
			info.setIs_give(goodsInfo.is_give());
			info.setPrice(goodsInfo.getPrice());
			info.setUnit(goodsInfo.getUnit());
			info.setTaste_types(goodsInfo.getTaste_types());
			info.setOrderTime(TimeUtils.getNowTime());
			infoList.add(info);
		}
		return infoList;
	}

	/**
	 * 当前已选数总数量
	 */
	private void setAlreadySelectNum()
	{
		if (activityDialogEnum == ActivityDialogEnum.FLAVOR)
		{
			tv_already.setText(Html.fromHtml("已选" + "<font color=#f04e39>" + getTotalNum() + "</font>" + goodsInfo.getUnit()));
			tv_totalPrice.setText(SaleUtils.getSaleString(getTotalNum() * goodsInfo.getPrice()));
		} else
		{
			String value = tv_content.getText().toString();
			if (is_goodsSwap)
			{
				int originalPrice = swapInfo.getQuantity() * swapInfo.getPrice();
				int currentPrice = Integer.parseInt(value) * goodsInfo.getPrice();
				if (currentPrice > originalPrice)
					tv_totalPrice.setText(SaleUtils.getSaleString(currentPrice - originalPrice));
				else
					tv_totalPrice.setText("0");
			} else
			{
				tv_totalPrice.setText(SaleUtils.getSaleString(Integer.parseInt(value) * goodsInfo.getPrice()));
			}
		}
	}

	/**
	 * 设置当前规格价格的显示
	 */
	private void setCurrentStandardPrice()
	{
		String value = tv_content.getText().toString();
		tv_totalPrice.setText(SaleUtils.getSaleString(Integer.parseInt(value) * goodsInfo.getPrice()));
	}

	@Override
	public void setValue(String value)
	{
		if (value.contains("."))
			ToastUtils.showText(OrderDialogActivity.this, R.string.error_number);
		else if (value.length() > 9)
			ToastUtils.showText(OrderDialogActivity.this, R.string.error_max_number);
		else if (Integer.parseInt(value) <= 0)
			ToastUtils.showText(OrderDialogActivity.this, R.string.error_number);
		else
		{
			if (activityDialogEnum == ActivityDialogEnum.FLAVOR)
			{
				for (int i = 0; i < views.size(); i++)
				{
					LinearLayout view = views.get(i);
					BaseEditText etView = (BaseEditText) view.findViewById(R.id.tv_content);
					int tag = (Integer) etView.getTag();
					if (tag == currentViewValue)
					{
						etView.setText(value);
						break;
					}
				}
			} else
			{
				tv_content.setText(value);
			}
		}
	}

	/**
	 * 根据类型获取不同的布局
	 *
	 * @param type
	 * @return
	 */
	private int getLayoutForType(ActivityDialogEnum type)
	{
		int returnValue = -1;
		switch (type)
		{
		case DEFAULT:
			returnValue = R.layout.common_dialog_no_flavor_two_toast;
			break;
		case SIZE:
			returnValue = R.layout.common_dialog_size_two_toast;
			break;
		case FLAVOR:
			returnValue = R.layout.common_dialog_flavor_two_toast;
			break;
		case PACKAGE_TYPE:
			returnValue = R.layout.common_dialog_no_flavor_two_toast;
			break;
		default:
			returnValue = -1;
		}
		return returnValue;
	}

}
